﻿using IOP.SgrA;
using IOP.SgrA.Input;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Options;
using Silk.NET.Vulkan;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;

namespace VkSample71
{
    public class SecondaryRenderingMiddleware : IProductionLineMiddleware<SecondaryVulkanRenderGroup>
    {

        public SecondaryRenderingMiddleware()
        {
        }

        public void Invoke(SecondaryVulkanRenderGroup group, RenderingProductionLineDelegate<SecondaryVulkanRenderGroup> next)
        {
            var camera = group.Camera;
            var view = camera.ViewMatrix;
            var project = camera.ProjectionMatrix;
            var cmd = group.SecondaryCommandBuffer;
            CommandBufferInheritanceInfo info = new CommandBufferInheritanceInfo
            {
                Framebuffer = group.Framebuffer.RawHandle,
                OcclusionQueryEnable = false,
                RenderPass = group.RenderPass.RawHandle,
                Subpass = 0
            };
            cmd.Reset();
            cmd.Begin(CommandBufferUsageFlags.CommandBufferUsageOneTimeSubmitBit | 
                CommandBufferUsageFlags.CommandBufferUsageRenderPassContinueBit, info);
            cmd.BindPipeline(PipelineBindPoint.Graphics, group.Pipeline);
            cmd.SetViewport(new Viewport(0, 0, camera.Viewport.Width, camera.Viewport.Height, 0, 1));
            cmd.SetScissor(new Rect2D(new Offset2D(0, 0), new Extent2D((uint)camera.Viewport.Width, (uint)camera.Viewport.Height)));

            foreach (var item in group.GetContexts())
            {
                item.SetViewMatrix(in view);
                item.SetProjectionMatrix(in project);
                group.ItemProductionLine(item);
            }
            group.SecondaryCommandBuffer.End();
        }
    }
}
